/**
 * @Description: API接口配置和请求封装 - 使用模拟API服务
 * @Author: lujq
 * @Date: 2025-01-04
 * @LastEditors: lujq
 * @LastEditTime: 2025-01-04 18:00:00
 */

import type { ApiResponse } from '@/types'
import { mockApi } from '@/utils/mockApi'
import { ElMessage } from 'element-plus'

// 模拟HTTP请求的延迟和错误处理
const simulateHttpRequest = async <T>(
  apiCall: () => Promise<ApiResponse<T>>
): Promise<ApiResponse<T>> => {
  try {
    const response = await apiCall()
    
    // 模拟网络错误（可选）
    if (Math.random() < 0.01) { // 1% 概率模拟网络错误
      throw new Error('网络连接失败')
    }
    
    return response
  } catch (error) {
    console.error('API请求失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '请求失败')
    throw error
  }
}

// 解析URL和参数的工具函数
const parseUrl = (url: string) => {
  const [path, queryString] = url.split('?')
  const params: Record<string, any> = {}
  
  if (queryString) {
    const urlParams = new URLSearchParams(queryString)
    for (const [key, value] of urlParams.entries()) {
      // 尝试解析数字
      if (!isNaN(Number(value))) {
        params[key] = Number(value)
      } else if (value === 'true' || value === 'false') {
        params[key] = value === 'true'
      } else {
        params[key] = value
      }
    }
  }
  
  return { path, params }
}

// 从URL路径中提取资源名称和ID
const parseResourcePath = (path: string) => {
  const segments = path.split('/').filter(Boolean)
  const resource = segments[0]
  const id = segments[1]
  return { resource, id }
}

// 通用请求方法
export const http = {
  /**
   * GET请求 - 获取数据
   */
  async get<T = any>(url: string): Promise<ApiResponse<T>> {
    return simulateHttpRequest(async () => {
      const { path, params } = parseUrl(url)
      const { resource, id } = parseResourcePath(path)
      
      if (id) {
        // 获取单个资源
        return await mockApi.getById<T>(resource, id)
      } else {
        // 获取资源列表
        return await mockApi.getList<T>(resource, params)
      }
    })
  },

  /**
   * POST请求 - 创建数据
   */
  async post<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return simulateHttpRequest(async () => {
      const { path } = parseUrl(url)
      const { resource } = parseResourcePath(path)
      
      return await mockApi.create<T>(resource, data)
    })
  },

  /**
   * PUT请求 - 更新数据
   */
  async put<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return simulateHttpRequest(async () => {
      const { path } = parseUrl(url)
      const { resource, id } = parseResourcePath(path)
      
      if (!id) {
        throw new Error('PUT请求需要指定资源ID')
      }
      
      return await mockApi.update<T>(resource, id, data)
    })
  },

  /**
   * DELETE请求 - 删除数据
   */
  async delete<T = any>(url: string): Promise<ApiResponse<T>> {
    return simulateHttpRequest(async () => {
      const { path, params } = parseUrl(url)
      const { resource, id } = parseResourcePath(path)
      
      if (id) {
        // 删除单个资源
        return await mockApi.delete(resource, id) as ApiResponse<T>
      } else if (params.ids) {
        // 批量删除
        const ids = Array.isArray(params.ids) ? params.ids : [params.ids]
        return await mockApi.batchDelete(resource, ids) as ApiResponse<T>
      } else {
        throw new Error('DELETE请求需要指定资源ID或批量ID')
      }
    })
  },

  /**
   * PATCH请求 - 部分更新数据
   */
  async patch<T = any>(url: string, data?: any): Promise<ApiResponse<T>> {
    return simulateHttpRequest(async () => {
      const { path } = parseUrl(url)
      const { resource, id } = parseResourcePath(path)
      
      if (!id) {
        throw new Error('PATCH请求需要指定资源ID')
      }
      
      return await mockApi.update<T>(resource, id, data)
    })
  }
}

// 导出模拟API实例供直接使用
export { mockApi }
export default http
